package edu.scau.mis.pos.service.impl;

import edu.scau.mis.pos.domain.Payment;
import edu.scau.mis.pos.mapper.*;
import edu.scau.mis.pos.domain.Order;
import edu.scau.mis.pos.domain.Change;
import edu.scau.mis.pos.domain.OrderItem;
import edu.scau.mis.pos.service.IOrderService;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private PaymentMapper paymentMapper;


    @Resource
    private ChangeMapper exchangeMapper; // ✅ 新增换货表的Mapper注入

    @Override
    public List<Order> listOrders(String orderId, String payType, String startTime, String endTime, Integer status, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return orderMapper.selectOrderList(orderId, payType, startTime, endTime, status, offset, pageSize);
    }

    @Override
    public int countOrders(String orderId, String payType, String startTime, String endTime, Integer status) {
        return orderMapper.countOrderList(orderId, payType, startTime, endTime, status);
    }

    @Override
    public Order getOrderById(String orderId) {
        return orderMapper.selectOrderById(orderId);
    }

    @Override
    public List<OrderItem> getOrderItemsByOrderId(String orderId) {
        return orderMapper.selectOrderItemsByOrderId(orderId);
    }

    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    @Override
    public int deleteOrder(String orderId) {
        orderMapper.deleteOrderItems(orderId); // 先删除明细表
        return orderMapper.deleteOrder(orderId); // 再删除主表
    }

    @Override
    public int deleteOrders(List<String> orderIds) {
        for (String orderId : orderIds) {
            deleteOrder(orderId);
        }
        return 1;
    }

    @Override
    public int refundOrder(String orderId) {
        // 1️⃣ 获取所有订单明细
        List<OrderItem> orderItems = orderMapper.selectOrderItemsByOrderId(orderId);

        // 2️⃣ 按明细恢复库存和销量
        for (OrderItem item : orderItems) {
            productMapper.increaseStockQuantity(item.getSkuCode(), item.getQuantity());  // SKU库存
            productMapper.decreaseSalesAndIncreaseStock(item.getProductSn(), item.getQuantity()); // 商品销量减少 + 商品库存增加
        }
        // 3️⃣ 更新订单状态为已退货（你在 mapper 里定义好的逻辑）
        return orderMapper.refundOrder(orderId);
    }



    @Override
    public int changeOrder(String orderId) {
        // 1️⃣ 获取订单信息
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // ✅ 不再执行任何库存和销量操作

        // 2️⃣ 生成换货编号和换货时间
        String changeSn = "EX" + System.currentTimeMillis();
        Date changeTime = new Date();

        // 3️⃣ 新建换货记录
        Change change = new Change();
        change.setChangeSn(changeSn);
        change.setOrderId(orderId);
        change.setUserName(order.getUserName());
        change.setAmount(order.getAmount());
        change.setTotalAmount(order.getTotalAmount());
        change.setTotalQuantity(order.getTotalQuantity());
        change.setPromotionType(order.getPromotionType());
        change.setContent(order.getContent());
        change.setPayType(order.getPayType());
        change.setPaymentTime(order.getPaymentTime());
        change.setChangeTime(changeTime);
        change.setStatus(3);  // 换货中

        // 4️⃣ 插入换货记录
        exchangeMapper.insertChange(change);

        // 5️⃣ 更新订单状态为“换货中”
        return orderMapper.updateOrderStatus(orderId, 3);
    }




    @Override
    public boolean createOrder(Order order) {
        // 1️⃣ 检查 orderId 是否存在
        if (order.getOrderId() == null || order.getOrderId().isEmpty()) {
            throw new IllegalArgumentException("Order ID 不能为空");
        }

        // 2️⃣ 设置默认值
        order.setStatus(0);  // 新订单默认状态为“未支付”
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        // 3️⃣ 插入数据库
        return orderMapper.insert(order) > 0;
    }

    @Override
    public OrderItem getOrderItemInfoBySkuCode(String skuCode) {
        return orderMapper.selectOrderItemInfoBySkuCode(skuCode);
    }

    @Override
    public int saveOrderItems(String orderId, List<OrderItem> items) {
        return orderMapper.insertOrderItems(orderId, items);
    }

    @Override
    public boolean processOrder(String orderId, String payType, Double amount, List<OrderItem> items, int status) {
        // 🔍 先查出原订单数据，用于保留 totalAmount 和 totalQuantity
        Order origin = orderMapper.selectOrderById(orderId);
        if (origin == null) {
            return false; // 没查到订单，直接失败
        }

        // ✅ 准备更新数据
        Order order = new Order();
        order.setOrderId(orderId);
        order.setPayType(payType);
        order.setAmount(amount); // 实际支付金额（打折后）
        order.setTotalAmount(origin.getTotalAmount());     // 保留原 totalAmount
        order.setTotalQuantity(origin.getTotalQuantity()); // 保留原 totalQuantity
        order.setStatus(status);

        if (status == 1) {
            order.setPaymentTime(new Date());
        }

        order.setUpdateTime(new Date());

        // ✅ 更新订单主表
        int update = orderMapper.updateOrderById(order);

        // ✅ 保存订单明细
        int insertItems = 0;
        if (items != null && !items.isEmpty()) {
            insertItems = orderItemMapper.insertOrderItems(orderId, items);
        }

        return update > 0 && insertItems == items.size();
    }




    @Override
    public boolean clearOrderItems(String orderId) {
        int deleted = orderItemMapper.deleteByOrderId(orderId);
        return deleted > 0;
    }

    @Override
    public boolean simulatePayment(String orderId, String payType, Double amount) {
        Order order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            return false;
        }

        // 1️⃣ 更新订单状态为已支付
        order.setStatus(1); // 1 表示已支付
        order.setPayType(payType);
        order.setAmount(amount); // 🔥 这里是打折后的总金额
        order.setPaymentTime(new Date());
        order.setUpdateTime(new Date());

        int updateResult = orderMapper.updateOrder(order);

        // 2️⃣ 插入支付记录到支付表
        if (updateResult > 0) {
            Payment payment = new Payment();
            payment.setPaymentId("PM" + System.currentTimeMillis());  // 🔥 生成支付流水号
            payment.setOrderId(orderId);
            payment.setAmount(amount);   // 🔥 这里是最终支付的价格
            payment.setPayType(payType);
            payment.setPayStatus("1");     // 🔥 1 表示支付成功
            payment.setPaymentTime(new Date());
            payment.setCreatedTime(new Date());
            payment.setUpdatedTime(new Date());

            // 插入到数据库
            paymentMapper.insertPayment(payment);

            List<OrderItem> orderItems = orderMapper.selectOrderItemsByOrderId(orderId);
            for (OrderItem item : orderItems) {
                productMapper.decreaseStockQuantity(item.getSkuCode(), item.getQuantity());  // SKU库存减少
                productMapper.increaseSalesAndDecreaseStock(item.getProductSn(), item.getQuantity()); // 商品销量增加 + 库存减少
            }

            return true;
        }

        return false;
    }




}

